<?php

namespace App\Criteria\System\User;

use App\Libs\Tools\DataTables;
use App\Libs\Tools\SystemCodeConstant;
use Illuminate\Support\Facades\Input;
use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

class UserBaseQueryCriteria implements CriteriaInterface{

    public function apply($model, RepositoryInterface $repository){
        $name=Input::get('name');
        $major_department_id=Input::get('major_department_id');
        $station_id=Input::get('station_id');
        $teacher=Input::get('teacher');
        if($name){$model = $model->where('users.name','like', '%'.$name.'%');}
        if($major_department_id){$model = $model->where('users.major_department_id','=', $major_department_id);}
        $model=$model->leftJoin('department', 'users.major_department_id', '=', 'department.id')
                     ->leftJoin('station', 'users.major_station_id', '=', 'station.id')
                     ->select('users.*', 'department.name as major_department_name', 'station.name as major_station_name');
        if($station_id){
            $model->leftJoin('user_station', 'users.id', '=', 'user_station.user_id')
                  ->where('user_station.station_id','=',$station_id);
        }
        if($teacher){
            $model->where('users.account_type','=',SystemCodeConstant::ACCOUNT_TYPE_TEACHER);
        }

        $order_column_tag=DataTables::get_order_column_tag();
        if(!is_null($order_column_tag)){
            $model->orderBy($order_column_tag['order_column'],$order_column_tag['order_type']);
        }
        return $model;
    }

}